package com.sx.rabbitmqtest.mq;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @author shengx
 * @date 2020/8/12 20:22
 */
@Configuration
public class RabbitMQConfig {

    public static final String RABBIT_EXCHANGE_TTL = "rabbit.exchange.ttl";
    public static final String RABBIT_EXCHANGE_DL = "rabbit.exchange.dxl";
    public static final String RABBIT_QUEUE_TTL = "rabbit.queue.ttl";
    public static final String RABBIT_QUEUE_DL = "rabbit.queue.dxl";
    public static final String DL_ROUTING_KEY = "rabbit.route.dl";
    public static final String TTL_ROUTING_KEY = "rabbit.route.ttl";

    @Bean("ttlExchange")
    public DirectExchange ttlExchange(){
        return new DirectExchange(RABBIT_EXCHANGE_TTL);
    }

    @Bean("dlExchange")
    public DirectExchange dlExchange(){
        return new DirectExchange(RABBIT_EXCHANGE_DL);
    }

    @Bean("ttlQueue")
    public Queue ttlQueue(){
        Map<String, Object> args = new HashMap<>(2);
        // x-dead-letter-exchange    这里声明当前队列绑定的死信交换机
        args.put("x-dead-letter-exchange", RABBIT_EXCHANGE_DL);
        // x-dead-letter-routing-key  这里声明当前队列的死信路由key
        args.put("x-dead-letter-routing-key", DL_ROUTING_KEY);
        // x-message-ttl  声明队列的TTL
        args.put("x-message-ttl", 15000);
        return QueueBuilder.durable(RABBIT_QUEUE_TTL).withArguments(args).build();
    }

    @Bean("dlQueue")
    public Queue dlQueue(){
        return QueueBuilder.durable(RABBIT_QUEUE_DL).build();
    }

    @Bean
    public Binding ttlBinding(@Qualifier("ttlQueue") Queue queue, @Qualifier("ttlExchange") DirectExchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with(TTL_ROUTING_KEY);
    }

    @Bean
    public Binding dlBinding(@Qualifier("dlQueue") Queue queue, @Qualifier("dlExchange") DirectExchange exchange){
        return BindingBuilder.bind(queue).to(exchange).with(DL_ROUTING_KEY);
    }

}
